<template>
  <div style="width: 80%; margin: 10px auto">

    <div style="margin-bottom: 20px">
      <el-radio-group v-model="data.type">
        <el-radio label="宠物订单" value="pet">
          宠物订单
        </el-radio>
        <el-radio label="宠物用品订单" value="goods">
          宠物用品订单
        </el-radio>
      </el-radio-group>
    </div>

    <!--宠物订单-->
    <div class="card" style="padding: 20px" v-if="data.type === 'pet'">
      <div style="margin-bottom: 20px">
        <el-input v-model="data.orderNo" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入订单号"></el-input>
        <el-select placeholder="请选择订单状态" v-model="data.status" style="width: 240px; margin-right: 10px">
          <el-option label="已取消" value="已取消"></el-option>
          <el-option label="待支付" value="待支付"></el-option>
          <el-option label="待发货" value="待发货"></el-option>
          <el-option label="待签收" value="待签收"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
        </el-select>
        <el-input v-model="data.petName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入宠物名称"></el-input>
        <el-input v-model="data.shopName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入宠物店名称"></el-input>
        <el-button type="info" plain @click="load">查询</el-button>
        <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
      </div>
      <div style="margin-bottom: 20px">
        <el-table stripe :data="data.tableData">
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="shopName" label="宠物店">
            <template #default="scope">
              <div style="cursor: pointer" @click="router.push('/front/petShopDetail?id=' + scope.row.shopId)">
                {{ scope.row.shopName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="petName" label="宠物名称">
            <template #default="scope">
              <div style="cursor: pointer" @click="router.push('/front/petDetail?id=' +  scope.row.petId)">
                {{ scope.row.petName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="petImage" label="宠物图片">
            <template #default="scope">
              <el-image style="width: 50px; height: 50px; border-radius: 5px" :src="scope.row.petImage" :preview-src-list="[scope.row.petImage]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="宠物价格"></el-table-column>
          <el-table-column prop="pickupAddress" label="收货人地址"></el-table-column>
          <el-table-column prop="status" label="订单状态">
            <template v-slot="scope">
              <el-tag type="danger" v-if="scope.row.status === '已取消'">已取消</el-tag>
              <el-tag type="warning" v-if="scope.row.status === '待支付'">待支付</el-tag>
              <el-tag type="primary" v-if="scope.row.status === '待发货'">待发货</el-tag>
              <el-tag type="primary" v-if="scope.row.status === '待签收'">待签收</el-tag>
              <el-tag type="success" v-if="scope.row.status === '已完成'">已完成</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="190">
            <template #default="scope">
              <div style="display: flex; gap: 1px; justify-content: flex-end" v-if="scope.row.status !== '已完成'">
                <el-button type="primary" size="small" style="border-radius: 20px" :disabled=" scope.row.status !== '待支付' " @click="handleCancel(scope.row.id)">
                  取消
                </el-button>
                <el-button type="primary" size="small" style="border-radius: 20px" :disabled=" scope.row.status !== '待支付' " @click="handlePay(scope.row)">
                  支付
                </el-button>
                <el-button type="primary" size="small" style="border-radius: 20px" :disabled=" scope.row.status !== '待签收' " @click="handleSign(scope.row.id)">
                  签收
                </el-button>
              </div>
              <div v-else>
                <el-button type="primary" size="small" style="border-radius: 20px" @click="handleAgainPay(scope.row)">
                  再次购买
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="data.total">
        <el-pagination
            @current-change="load"
            @size-change="handleSizeChange"
            background layout="total, prev, pager, next, jumper, sizes"
            :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
            :page-size="data.pageSize"
            v-model:current-page="data.pageNum"
            :total="data.total"/>
      </div>
    </div>

    <!--收货人信息-->
    <el-dialog title="确认收货人信息" v-model="data.formVisible" width="45%" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.againOrders" label-width="90px" style="padding: 20px">
        <el-form-item prop="addressId" label="收货地址">
          <el-select style="width: 100%" v-model="data.againOrders.addressId">
            <el-option v-for="address in data.addressList" :key="address.id" :value="address.id" :label="address.name + ' - ' + address.address + ' - ' + address.phone"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="againPay">确 定</el-button>
        </span>
      </template>
    </el-dialog>


    <!--宠物用品订单-->
    <div class="card" style="padding: 20px" v-if="data.type === 'goods'">
      <div style="margin-bottom: 20px">
        <el-input v-model="goodsData.orderNo" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入订单号"></el-input>
        <el-select placeholder="请选择订单状态" v-model="goodsData.status" style="width: 240px; margin-right: 10px">
          <el-option label="已取消" value="已取消"></el-option>
          <el-option label="待支付" value="待支付"></el-option>
          <el-option label="待发货" value="待发货"></el-option>
          <el-option label="待签收" value="待签收"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
        </el-select>
        <el-input v-model="goodsData.goodsName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入宠物用品名称"></el-input>
        <el-input v-model="goodsData.shopName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入宠物店名称"></el-input>
        <el-button type="info" plain @click="loadGoodsOrders">查询</el-button>
        <el-button type="warning" plain style="margin: 0 10px" @click="resetGoodsOrders">重置</el-button>
      </div>
      <div style="margin-bottom: 20px">
        <el-table stripe :data="goodsData.tableData">
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="shopName" label="宠物店">
            <template #default="scope">
              <div style="cursor: pointer" @click="router.push('/front/petShopDetail?id=' + scope.row.shopId)">
                {{ scope.row.shopName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsName" label="宠物用品名称"></el-table-column>
          <el-table-column prop="goodsImage" label="宠物用品图片">
            <template #default="scope">
              <el-image style="width: 50px; height: 50px; border-radius: 5px" :src="scope.row.goodsImage" :preview-src-list="[scope.row.goodsImage]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="宠物用品价格"></el-table-column>
          <el-table-column prop="goodsNumber" label="宠物用品数量"></el-table-column>
          <el-table-column prop="pickupAddress" label="收货人地址"></el-table-column>
          <el-table-column prop="status" label="订单状态">
            <template v-slot="scope">
              <el-tag type="danger" v-if="scope.row.status === '已取消'">已取消</el-tag>
              <el-tag type="warning" v-if="scope.row.status === '待支付'">待支付</el-tag>
              <el-tag type="primary" v-if="scope.row.status === '待发货'">待发货</el-tag>
              <el-tag type="primary" v-if="scope.row.status === '待签收'">待签收</el-tag>
              <el-tag type="success" v-if="scope.row.status === '已完成'">已完成</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="190">
            <template #default="scope">
              <div style="display: flex; gap: 1px; justify-content: flex-end">
                <el-button type="primary" size="small" style="border-radius: 20px" :disabled=" scope.row.status !== '待支付' " @click="handleGoodsCancel(scope.row.id)">
                  取消
                </el-button>
                <el-button type="primary" size="small" style="border-radius: 20px" :disabled=" scope.row.status !== '待支付' " @click="handleGoodsPay(scope.row)">
                  支付
                </el-button>
                <el-button type="primary" size="small" style="border-radius: 20px" :disabled=" scope.row.status !== '待签收' " @click="handleGoodsSign(scope.row.id)">
                  签收
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="goodsData.total">
        <el-pagination
            @current-change="loadGoodsOrders"
            @size-change="handleGoodsSizeChange"
            background layout="total, prev, pager, next, jumper, sizes"
            :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
            :page-size="goodsData.pageSize"
            v-model:current-page="goodsData.pageNum"
            :total="goodsData.total"/>
      </div>
    </div>
  </div>
</template>

<script setup>
  import {reactive, ref} from 'vue'
  import request from '@/utils/request.js'
  import {ElMessage, ElMessageBox} from 'element-plus'
  import router from "@/router/index.js";

  const formRef = ref()

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    type: 'pet',
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    status: null,
    petName: null,
    shopName: null,
    tableData: [],
    total: 0,
    againOrders: {
      shopId: null,
      petId: null,
      addressId: null
    },
    addressList: [],
    formVisible: false,
    rules: {
      addressId: [
        {required: true, message: '请选择收货人信息', trigger: 'blur'}
      ]
    }
  })

  const loadAddress = () => {
    request.get('address/query/all', {
      params: {
        userId: data.user.id
      }
    }).then(res => {
      if (res.code === '200') {
        data.addressList = res.data
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const load = () => {
    request.get('/petOrders/pageQuery', {
      params:{
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        orderNo: data.orderNo,
        petName: data.petName,
        shopName: data.shopName,
        status: data.status
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list || []
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const reset = () => {
    data.orderNo = null
    data.petName = null
    data.shopName = null
    data.status = null
    load()
  }

  const handleSizeChange = (newSize) => {
    data.pageSize = newSize
    data.pageNum = 1  // 切换页大小时重置到第一页
    load()
  }

  // 普通用户取消订单
  const handleCancel = (id) => {
    ElMessageBox.confirm('您确认取消订单吗?', '确认取消', {type: 'warning'}).then(res => {
      request.put('/petOrders/cancel?id=' + id).then(res => {
        if (res.code === '200') {
          ElMessage.success('取消订单成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }

  // 普通用户支付订单
  const handlePay = (row) => {
    ElMessageBox.confirm('您确认支付' + row.price + '元吗？账户余额不足将支付失败', '支付确认', { type: 'warning' }).then(res => {
      request.put('/petOrders/pay?id=' + row.id).then(res => {
        if (res.code === '200') {
          ElMessage.success('支付成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }

  // 普通用户签收
  const handleSign = (id) => {
    request.put('/petOrders/sign?id=' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('签收成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 再次购买
  const handleAgainPay = (row) => {
    data.formVisible = true;
    data.againOrders.petId = row.petId
    data.againOrders.shopId = row.shopId
  }

  // 再次购买
  const againPay = () => {
    formRef.value.validate(valid => {
      if (valid) {
        request.post('petOrders/add', {
          shopId: data.againOrders.shopId,
          petId: data.againOrders.petId,
          addressId: data.againOrders.addressId
        }).then(res => {
          if (res.code === '200') {
            data.formVisible = false
            ElMessage.success('再次购买成功')
            load()
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }

  load()
  loadAddress()

  //**********************************宠物用品******************************************

  const goodsData = reactive({
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    status: null,
    goodsName: null,
    shopName: null,
    tableData: [],
    total: 0,
  })

  const loadGoodsOrders = () => {
    request.get('/goodsOrders/pageQuery', {
      params:{
        pageNum: goodsData.pageNum,
        pageSize: goodsData.pageSize,
        orderNo: goodsData.orderNo,
        goodsName: goodsData.goodsName,
        shopName: goodsData.shopName,
        status: goodsData.status
      }
    }).then(res => {
      if (res.code === '200') {
        goodsData.tableData = res.data?.list || []
        goodsData.total = res.data.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  loadGoodsOrders()

  const resetGoodsOrders = () => {
    goodsData.orderNo = null
    goodsData.status = null
    goodsData.goodsName = null
    goodsData.shopName = null
    loadGoodsOrders()
  }

  const handleGoodsSizeChange = (newSize) => {
    goodsData.pageSize = newSize
    goodsData.pageNum = 1  // 切换页大小时重置到第一页
    loadGoodsOrders()
  }

  const handleGoodsCancel = (id) => {
    request.put('/goodsOrders/cancel?id=' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('取消订单成功')
        loadGoodsOrders()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const handleGoodsPay = (row) => {
    ElMessageBox.confirm('您确认支付' + row.price * row.goodsNumber + '元吗？账户余额不足将支付失败', '支付确认', {type: 'warning'}).then(res => {
      request.put('/goodsOrders/pay?id=' + row.id).then(res => {
        if (res.code === '200') {
          ElMessage.success('支付成功')
          loadGoodsOrders()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }

  const handleGoodsSign = (id) => {
    request.put('/goodsOrders/sign?id=' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('签收成功')
        loadGoodsOrders()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
</script>